<template>
	<div class="course_learn_player">
		<div class="exam" v-if="isLearnFinish">
			<h4>您正在查看的培训课程已经学习完成</h4>
			<div class="button">
				<el-button type="warning" size="medium" @click="handleRestudyCourse()">重新学习</el-button>
				<el-button type="primary" size="medium" @click="handleStartExam()">马上考试</el-button>
			</div>
		</div>
		<el-empty v-else-if="!fileUrl" :image-size="100" :image="novideo">
			<template slot="description">暂无学习数据，请联系管理员添加</template>
		</el-empty>
		<template v-else-if="data.type === '6'">
			<video-player v-bind="playerConfig" :file-src="fileUrl" :data="data" />
		</template>
		<template v-else-if="data.type === '7'">
			<document-player v-bind="playerConfig" :file-src="fileUrl" :data="data" />
		</template>
	</div>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import { getStudyProgress } from '@/api/openApi';
import videoPlayer from '@/components/player/video';
import documentPlayer from '@/components/player/document';
import { addedLearnProgress, updateLearnProgress, batchDeleteProgress } from '@/api/front/sysLearningProgress';
export default {
	components: { videoPlayer, documentPlayer },
	props: {
		list: { type: Array, default: () => [] },
		data: { type: Object, default: () => {} },
		period: { type: [String, Number] }
	},
	data() {
		return {
			learnProgress: {},
			playerConfig: {
				playEnd: this.handlePlayerEnd,
				playStart: this.handlePlayerStart,
				timeUpdate: this.handleTimeUpdate
			},
			novideo: require('@/assets/img/novideo.svg')
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		courseId() {
			return this.$route.params.id;
		},
		chapterId() {
			return this.$route.query.drama;
		},
		fileUrl() {
			let httpUrl = this.data.sysAttachment?.httpUrl;
			return !httpUrl ? '' : httpUrl.replaceIP();
		},
		isLearnFinish() {
			return this.$route.query.type === 'exam';
		},
		chapterNodes() {
			let chapters = this.$treeToFlat(this.list, 'childList');
			let nodeFilter = chapters.filter((item) => item.type === '2');
			return nodeFilter.sort((a, b) => a.sort - b.sort);
		},
		progressParams() {
			let courseId = this.courseId;
			let chapterId = this.chapterId;
			let knowledgeId = this.data.id;
			let userName = this.userInfo.id;
			return { courseId, chapterId, knowledgeId, userName };
		}
	},
	watch: {
		data(data) {
			this.getLearnProgressData();
		}
	},
	methods: {
		//获取学习进度数据
		async getLearnProgressData() {
			let page = { page: 1, limit: 1 };
			let params = { ...this.progressParams, ...page };
			let result = await getStudyProgress(params).then((res) => res.data);
			if (result.code === '0') {
				this.learnProgress = this.$detailData(result.data);
			}
		},

		//添加学习进度数据
		async addedLearnProgressData() {
			let params = { ...this.progressParams, status: 0 };
			let result = await addedLearnProgress(params).then((res) => res.data);
			if (result.code === '0') {
				this.learnProgress = this.$detailData(result.data);
			}
		},

		//更新学习进度数据
		async updateLearnProgressData(anchorPoint, status) {
			updateLearnProgress({ ...this.learnProgress, anchorPoint, status });
		},

		//播放开始
		handlePlayerStart(player) {
			if (lodash.isEmpty(this.learnProgress)) {
				this.addedLearnProgressData();
			}
		},

		//播放时间更新
		handleTimeUpdate(time) {
			let status = this.learnProgress.status || 0;
			let anchorPoint = parseFloat(this.learnProgress.anchorPoint) || 0;
			let timeStatus = time !== 0 && time % 10 === 0 && time > anchorPoint;
			if (!!timeStatus && status == 0 && !lodash.isEmpty(this.learnProgress)) {
				this.updateLearnProgressData(time, 0);
			}
		},

		//播放结束
		handlePlayerEnd(time) {
			let path = this.$route.path;
			let status = this.learnProgress.status || 0;
			let index = this.chapterNodes.findIndex((n) => n.id === this.chapterId);
			if (index + 1 === this.chapterNodes.length) {
				let resId = this.courseId;
				let duration = this.period || 0;
				let params = { resId, durationType: 'C', duration };
				this.$store.dispatch('addedDurationRecord', params);
				this.$router.replace({ path, query: { type: 'exam' } });
			} else {
				let nextNode = this.chapterNodes[index + 1] || {};
				this.$router.replace({ path, query: { type: 'learn', drama: nextNode.id } });
			}
			status == 0 && this.updateLearnProgressData(time, 1);
		},

		//重新开始学习
		async handleRestudyCourse() {
			let path = this.$route.path;
			let page = { page: 1, limit: 999 };
			let params = lodash.pick(this.progressParams, ['courseId', 'userName']);
			let result = await getStudyProgress({ ...page, ...params }).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				let curNode = this.chapterNodes[0] || {};
				if (datas.length > 0) {
					await this.deleteProgressRequest(datas);
				}
				this.$router.replace({ path, query: { type: 'learn', drama: curNode.id } });
			}
		},

		//批量删除课程进度
		async deleteProgressRequest(arr) {
			let params = arr.map((n) => n.id);
			await batchDeleteProgress(params);
		},

		//点击马上考试
		async handleStartExam() {
			let params = { courseId: this.courseId };
			let courseExam = await this.$store.dispatch('getCourseExamData', params);
			if (lodash.isEmpty(courseExam)) {
				this.$message.warning('该课程未设置考试，请联系管理员设置考试！');
			} else {
				this.$bus.$emit('examConfirm', courseExam.examId);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.course_learn_player::v-deep {
	width: 100%;
	position: relative;
	&::before {
		display: block;
		content: '';
		width: 100%;
		background-color: #000;
	}
	&:has(.exam)::before,
	&:has(.el-empty)::before,
	&:has(.video_player)::before {
		padding-top: 56.25%;
	}
	&:has(.document_player)::before {
		padding-top: 76.25%;
	}
	.exam,
	.el-empty,
	.video_player,
	.document_player {
		position: absolute;
		top: 0;
		left: 0;
	}
	.exam,
	.el-empty {
		margin: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
	}
	.exam h4 {
		color: #606266;
		font-size: 18px;
		font-weight: normal;
		margin-bottom: 16px;
	}
}
@media (min-width: 992px) {
	.course_learn_player {
		width: calc(100% - 315px);
	}
}
</style>
